const xml2js = require('xml2js');
const fs = require('fs');

const AmazonMwsStub = function(action, xmlPathList) {
  const responseStringList = [];
  xmlPathList.forEach(xmlPath => {
    responseStringList.push(fs.readFileSync(xmlPath, 'utf8'));
  });
  this.mockupCall = function(index) {
    return function(sellerId, mwsAuthToken, marketplaceidList) {
      const xmlParser = new xml2js.Parser({
        mergeAttrs: true,
        explicitArray: false,
        emptyTag: {},
        charkey: 'Value'
      });

      return xmlParser.parseStringPromise(responseStringList[index]).then((response, error) => {
        const data = response[action + "Response"][action + "Result"];
        const headers = {
          "server": "Server",
          "date": "Sat, 15 Aug 2020 09:21:17 GMT",
          "content-type": "text/xml",
          "content-length": "346",
          "connection": "close",
          "x-amz-rid": "E56RY7VAG01YPNFXSADZ",
          "x-amz-date": "Sat, 15 Aug 2020 09:21:17 GMT",
          "x-amzn-authorization": "AAA identity=com.amazon.aaa.MarketplaceWebServiceOrders.AndromedaControlService.amzn1.aaa.id.qhz3ylg755gkejyk5sh44qm3wy.Default/1, Operation=ListOrders, Service=MarketplaceWebServiceOrders, Encrypted=false, SignedHeaders=X-Amz-Date, Algorithm=HmacSHA256, Signed=true, Signature=BxWUZF+pkheV1uj2w3pndVOEnq4E5N31AezcmJIhjWg=,RelationshipVersion=0",
          "x-mws-request-id": "b30edf4f-2364-4409-9478-74716d408865",
          "x-mws-timestamp": "2020-08-15T09:21:17.630Z",
          "x-mws-response-context": "4jgflZqc5TJKstGc//2YFv4SA28/0FbpJVj+hhbpcQ3IcJfmvC+d5kPq+XyIT5E6du9pOrAvIGE=",
          "vary": "Content-Type,Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent"
        };
        const statusCode = 200;
        const contentType = "text/xml";
        const r = Object.assign(data, {
          "ResponseMetadata": response.ResponseMetadata || {},
          "StatusCode": statusCode,
          "Headers": headers,
        });
        return r;
      });
    };
  };
};

module.exports = AmazonMwsStub;